package site.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.n3r.eql.EqlPage;

import site.annotations.LoginIgnoreMethod;
import site.annotations.LoginVerifyAction;
import site.config.CommonConfig;
import site.exception.MessageException;
import site.service.WorksService;
import site.util.Collections;
import site.util.CommonUtils;
import site.util.UploadCommon;

import com.alibaba.fastjson.util.Base64;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.opensymphony.xwork2.ActionSupport;

@LoginVerifyAction
public class WorksAction extends ActionSupport {
    private Map resMap;
    private String image;
    private String fileName;
    private String imageSrc;
    private int imageWidth;
    private int imageHeigth;
    private String bannerFlag = "0";
    private String worksType;
    private String worksName;
    private String worksWidth;
    private String worksHeigh;
    private String worksSign;
    private String worksSeal;
    private String worksMaterial;
    private String worksYears;
    private String worksForm;
    private String worksDesc;

    private String worksId;
    private String uploadFlag;

    private String currentPage;
    EqlPage eqlPage = new EqlPage();

    private static final List IMAGELIST = Lists.newArrayList("jpg", "jpeg", "bmp");
    private static final int IMAGE_WIDTH = 237;

    private String newFileName = "";
    private String smallFileName = "";
    @Resource
    private WorksService worksService;

    @Action(value = "/works/list", results = { @Result(name = "success", type = "freemarker", location = "/pages/works/WorksList.ftl") })
    public String init() {
        eqlPage.setPageRows(CommonConfig.PAGE_ROWS);
        eqlPage.setCurrentPage(1);
        if (!Strings.isNullOrEmpty(currentPage)) {
            eqlPage.setCurrentPage(Integer.parseInt(currentPage));
        }
        resMap = worksService.queryWorksList(eqlPage);
        return SUCCESS;
    }

    @Action(value = "/works", results = { @Result(name = "success", type = "freemarker", location = "/pages/works/Works.ftl") })
    @LoginIgnoreMethod
    public String worksInit() {
        if (StringUtils.isBlank(worksType)) {
            worksType = "01";
        }
        resMap = worksService.queryWorksInfoList(worksType);
        return SUCCESS;
    }

    @Action(value = "/works/add", results = { @Result(name = "success", type = "freemarker", location = "/pages/works/WorksAdd.ftl") })
    public String addInit() {
        resMap = worksService.queryWorksPara();
        return SUCCESS;
    }

    @Action(value = "/works/setWorksBanner", results = { @Result(name = "success", type = "json", params = { "root",
            "resMap" }) })
    public String setWorksBanner() {
        if (StringUtils.isBlank(worksId)) {
            resMap = Collections.asMap("result", "fail");
            return SUCCESS;
        }
        int seccussNum = worksService.setWorksBanner(worksId);
        if (seccussNum == 1) {
            resMap = Collections.asMap("result", "success");
        } else {
            resMap = Collections.asMap("result", "fail");
        }
        return SUCCESS;
    }

    @Action(value = "/works/delWorksBanner", results = { @Result(name = "success", type = "json", params = { "root",
            "resMap" }) })
    public String delWorksBanner() {
        if (StringUtils.isBlank(worksId)) {
            resMap = Collections.asMap("result", "fail");
            return SUCCESS;
        }
        int seccussNum = worksService.delWorksBanner(worksId);
        if (seccussNum == 1) {
            resMap = Collections.asMap("result", "success");
        } else {
            resMap = Collections.asMap("result", "fail");
        }
        return SUCCESS;
    }

    @Action(value = "/works/delWorks", results = { @Result(name = "success", type = "json", params = { "root", "resMap" }) })
    public String delWorks() {
        if (StringUtils.isBlank(worksId)) {
            resMap = Collections.asMap("result", "fail");
            return SUCCESS;
        }
        int seccussNum = worksService.delWorks(worksId);
        if (seccussNum == 1) {
            resMap = Collections.asMap("result", "success");
        } else {
            resMap = Collections.asMap("result", "fail");
        }
        return SUCCESS;
    }

    @Action(value = "/works/addSubmit", results = {
            @Result(name = "success", type = "redirect", location = "/works/list"),
            @Result(name = "error", location = "/pages/moudle/Error.ftl") })
    public String addWorks() throws Exception {
        try {
            //图片上传
            pictureUpload();
            //数据入库
            String worksSize = worksWidth + "*" + worksHeigh;
            Map inMap = Collections.asMap("imageSrc", imageSrc, "imageWidth", IMAGE_WIDTH, "imageHeigth", imageHeigth,
                    "bannerFlag", bannerFlag, "worksType", worksType, "worksName", worksName, "worksAuthor", "寇克让",
                    "worksSize", worksSize, "worksSeal", worksSeal, "worksSign", worksSign, "worksMaterial",
                    worksMaterial, "worksYears", worksYears, "worksForm", worksForm, "worksDesc", worksDesc);
            int num = worksService.addWorks(inMap);
            if (num == 1) {
                return SUCCESS;
            }
        } catch (IOException e) {
            throw new MessageException("图片上传失败！");
        }
        return ERROR;
    }

    private void pictureUpload() throws Exception, IOException {
        //图片上传
        if (StringUtils.isEmpty(image)) {
            throw new MessageException("图片上传失败！");
        }

        String extName = ""; // 文件拓展名
        if (fileName.lastIndexOf(".") >= 0) {
            extName = fileName.substring(fileName.lastIndexOf(".") + 1);
        }
        if (!UploadCommon.checkIsImage(extName, IMAGELIST)) {
            throw new MessageException("图片格式错误，仅支持jpg,jpeg,bmp格式图片！");
        }

        byte[] imageByte = getImgData(image);
        if (!UploadCommon.checkImageByteSize(imageByte, 2048)) {
            throw new MessageException("图片大小超过2M，请重新上传图片！");
        }

        String rannum = UploadCommon.getRanString();
        newFileName = rannum + "." + extName; //保存新的文件名
        smallFileName = rannum + "_s." + extName; //保存新的文件名
        String uploadPath = new CommonUtils().getImgUploadPath();
        File imageFile = new File(uploadPath + newFileName);
        FileUtils.writeByteArrayToFile(imageFile, imageByte);
        BufferedImage bi = ImageIO.read(imageFile);
        if (bi.getWidth() == 1024 && bi.getHeight() == 252) {
            bannerFlag = "1";
        }
        Builder<File> fileBu = Thumbnails.of(uploadPath + newFileName).size(IMAGE_WIDTH, 10000);
        fileBu.toFile(uploadPath + smallFileName);
        imageHeigth = fileBu.asBufferedImage().getHeight();
        imageSrc = "/images/upload/" + newFileName;
    }

    /**
     * 得到经过Base64解码的图像二进制数据
     */
    public byte[] getImgData(String fileUrl) {
        /*
         * 利用canvas元素的toDataURL("image/jpeg")方法生成的图像地址格式为：
         *  第一部分：data:image/jpeg;base64
         *  中间一个逗号
         *  第二部分：一个经过base64编码的字符串，通过Base64解码后即可得到该图像原始二进制数据
         */
        String[] data = fileUrl.split(",");//这里fileUrl就是前台toDataURL（）方法传过来的数据
        return Base64.decodeFast(data[1]);
    }

    @Action(value = "/works/edit", results = {
            @Result(name = "success", type = "freemarker", location = "/pages/works/WorksEdit.ftl"),
            @Result(name = "error", type = "freemarker", location = "/pages/moudle/Error.ftl") })
    public String editWorks() {
        if (StringUtils.isBlank(worksId)) {
            return ERROR;
        }
        resMap = worksService.queryWorksInfo(Collections.asMap("worksId", worksId));
        if (MapUtils.isEmpty(resMap) || MapUtils.isEmpty((Map) resMap.get("worksInfoMap"))) {
            return ERROR;
        }
        return SUCCESS;
    }

    @Action(value = "/works/editSubmit", results = {
            @Result(name = "success", type = "redirect", location = "/works/list"),
            @Result(name = "error", location = "/pages/moudle/Error.ftl") })
    public String editWorksSubmit() throws Exception {
        if (StringUtils.isBlank(worksId)) {
            return ERROR;
        }
        Map inMap = new HashMap();
        if ("1".equals(uploadFlag)) {
            //图片上传
            pictureUpload();
        }
        String worksSize = worksWidth + "*" + worksHeigh;
        inMap = Collections.asMap("worksId", worksId, "uploadFlag", uploadFlag, "imageSrc", imageSrc, "imageWidth",
                IMAGE_WIDTH, "imageHeigth", imageHeigth, "bannerFlag", bannerFlag, "worksType", worksType, "worksName",
                worksName, "worksSize", worksSize, "worksSeal", worksSeal, "worksSign", worksSign, "worksMaterial",
                worksMaterial, "worksYears", worksYears, "worksForm", worksForm, "worksDesc", worksDesc);
        int num = worksService.editWorksSubmit(inMap);
        if (num == 1) {
            return SUCCESS;
        }
        return ERROR;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getImageSrc() {
        return imageSrc;
    }

    public void setImageSrc(String imageSrc) {
        this.imageSrc = imageSrc;
    }

    public int getImageWidth() {
        return imageWidth;
    }

    public void setImageWidth(int imageWidth) {
        this.imageWidth = imageWidth;
    }

    public int getImageHeigth() {
        return imageHeigth;
    }

    public void setImageHeigth(int imageHeigth) {
        this.imageHeigth = imageHeigth;
    }

    public String getBannerFlag() {
        return bannerFlag;
    }

    public void setBannerFlag(String bannerFlag) {
        this.bannerFlag = bannerFlag;
    }

    public String getWorksType() {
        return worksType;
    }

    public void setWorksType(String worksType) {
        this.worksType = worksType;
    }

    public String getWorksName() {
        return worksName;
    }

    public void setWorksName(String worksName) {
        this.worksName = worksName;
    }

    public String getWorksWidth() {
        return worksWidth;
    }

    public void setWorksWidth(String worksWidth) {
        this.worksWidth = worksWidth;
    }

    public String getWorksHeigh() {
        return worksHeigh;
    }

    public void setWorksHeigh(String worksHeigh) {
        this.worksHeigh = worksHeigh;
    }

    public String getWorksSign() {
        return worksSign;
    }

    public void setWorksSign(String worksSign) {
        this.worksSign = worksSign;
    }

    public String getWorksSeal() {
        return worksSeal;
    }

    public void setWorksSeal(String worksSeal) {
        this.worksSeal = worksSeal;
    }

    public String getWorksMaterial() {
        return worksMaterial;
    }

    public void setWorksMaterial(String worksMaterial) {
        this.worksMaterial = worksMaterial;
    }

    public String getWorksYears() {
        return worksYears;
    }

    public void setWorksYears(String worksYears) {
        this.worksYears = worksYears;
    }

    public String getWorksForm() {
        return worksForm;
    }

    public void setWorksForm(String worksForm) {
        this.worksForm = worksForm;
    }

    public String getWorksDesc() {
        return worksDesc;
    }

    public void setWorksDesc(String worksDesc) {
        this.worksDesc = worksDesc;
    }

    public String getWorksId() {
        return worksId;
    }

    public void setWorksId(String worksId) {
        this.worksId = worksId;
    }

    public String getUploadFlag() {
        return uploadFlag;
    }

    public void setUploadFlag(String uploadFlag) {
        this.uploadFlag = uploadFlag;
    }

    public Map getResMap() {
        return resMap;
    }

    public void setResMap(Map resMap) {
        this.resMap = resMap;
    }

    public String getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(String currentPage) {
        this.currentPage = currentPage;
    }

}
